#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
中文字体显示优化模块
作者: 元歌
开发地: 广州南沙铁建中心
时间: 2024年10月
"""

import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import os
from typing import Tuple

# 全局字体缓存
_font_cache = {}

def load_chinese_font(font_size: int = 20) -> ImageFont.ImageFont:
    """
    加载中文字体，优化字体选择
    
    Args:
        font_size: 字体大小
        
    Returns:
        PIL字体对象
    """
    cache_key = f"chinese_font_{font_size}"
    if cache_key in _font_cache:
        return _font_cache[cache_key]
    
    font = None
    
    # 按优先级排序的字体路径
    font_paths = [
        # 微软雅黑系列（推荐）
        "C:/Windows/Fonts/msyh.ttc",      # 微软雅黑
        "C:/Windows/Fonts/msyhbd.ttc",    # 微软雅黑粗体
        "C:/Windows/Fonts/msyhl.ttc",     # 微软雅黑Light
        
        # 黑体系列
        "C:/Windows/Fonts/simhei.ttf",    # 黑体
        "C:/Windows/Fonts/simhei.ttc",    # 黑体
        
        # 宋体系列
        "C:/Windows/Fonts/simsun.ttc",    # 宋体
        "C:/Windows/Fonts/simsun.ttf",    # 宋体
        
        # 楷体系列
        "C:/Windows/Fonts/simkai.ttf",    # 楷体
        "C:/Windows/Fonts/simkai.ttc",    # 楷体
        
        # 仿宋系列
        "C:/Windows/Fonts/simfang.ttf",   # 仿宋
        "C:/Windows/Fonts/simfang.ttc",   # 仿宋
        
        # 华文系列
        "C:/Windows/Fonts/STZHONGS.TTF",  # 华文中宋
        "C:/Windows/Fonts/STKAITI.TTF",   # 华文楷体
        "C:/Windows/Fonts/STSONG.TTF",    # 华文宋体
        "C:/Windows/Fonts/STFANGSO.TTF",  # 华文仿宋
        
        # 其他中文字体
        "C:/Windows/Fonts/DFKai-SB.ttf",  # 标楷体
        "C:/Windows/Fonts/DFKai-SB.ttc",  # 标楷体
    ]
    
    for font_path in font_paths:
        if os.path.exists(font_path):
            try:
                font = ImageFont.truetype(font_path, font_size)
                print(f"✅ 成功加载中文字体: {os.path.basename(font_path)} (大小: {font_size})")
                break
            except Exception as e:
                continue
    
    if font is None:
        # 尝试使用系统默认字体
        try:
            # Windows 10/11 默认字体
            font = ImageFont.truetype("segoeui.ttf", font_size)
            print(f"⚠️  使用系统默认字体: segoeui.ttf (大小: {font_size})")
        except:
            try:
                # 备用字体
                font = ImageFont.truetype("arial.ttf", font_size)
                print(f"⚠️  使用备用字体: arial.ttf (大小: {font_size})")
            except:
                # 最后使用PIL默认字体
                font = ImageFont.load_default()
                print(f"❌ 使用PIL默认字体 (大小: {font_size}) - 可能不支持中文")
    
    # 缓存字体
    _font_cache[cache_key] = font
    return font

def draw_chinese_text_enhanced(image: np.ndarray, text: str, position: Tuple[int, int], 
                              font_size: int = 20, color: Tuple[int, int, int] = (255, 255, 255),
                              background_color: Tuple[int, int, int] = None,
                              background_padding: int = 5) -> np.ndarray:
    """
    增强版中文文字绘制函数
    
    Args:
        image: 输入图像 (BGR格式)
        text: 要绘制的文字
        position: 文字位置 (x, y)
        font_size: 字体大小
        color: 文字颜色 (BGR格式)
        background_color: 背景颜色 (BGR格式)，None表示无背景
        background_padding: 背景内边距
        
    Returns:
        绘制后的图像
    """
    if not text or not text.strip():
        return image
    
    try:
        # 转换BGR到RGB
        image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        pil_image = Image.fromarray(image_rgb)
        draw = ImageDraw.Draw(pil_image)
        
        # 加载中文字体
        font = load_chinese_font(font_size)
        
        # 转换颜色格式 (BGR -> RGB)
        text_color = (color[2], color[1], color[0])
        
        # 如果有背景色，先绘制背景
        if background_color is not None:
            # 获取文字尺寸
            bbox = draw.textbbox(position, text, font=font)
            text_width = bbox[2] - bbox[0]
            text_height = bbox[3] - bbox[1]
            
            # 计算背景矩形
            bg_x1 = position[0] - background_padding
            bg_y1 = position[1] - background_padding
            bg_x2 = position[0] + text_width + background_padding
            bg_y2 = position[1] + text_height + background_padding
            
            # 转换背景颜色 (BGR -> RGB)
            bg_color = (background_color[2], background_color[1], background_color[0])
            
            # 绘制背景
            draw.rectangle([bg_x1, bg_y1, bg_x2, bg_y2], fill=bg_color)
        
        # 绘制文字
        draw.text(position, text, font=font, fill=text_color)
        
        # 转换回BGR格式
        image_bgr = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
        return image_bgr
        
    except Exception as e:
        print(f"❌ 中文文字绘制出错: {e}")
        # 如果绘制失败，返回原图像
        return image

def create_info_panel_chinese(image: np.ndarray, info_dict: dict, 
                             position: Tuple[int, int] = (10, 10)) -> np.ndarray:
    """
    创建中文信息面板
    
    Args:
        image: 输入图像
        info_dict: 信息字典
        position: 面板位置
        
    Returns:
        添加信息面板后的图像
    """
    x, y = position
    line_height = 25
    current_y = y
    
    # 创建半透明背景
    overlay = image.copy()
    cv2.rectangle(overlay, (x-5, y-5), (x+450, y+200), (0, 0, 0), -1)
    cv2.addWeighted(overlay, 0.7, image, 0.3, 0, image)
    
    # 绘制标题
    title_text = "🎯 姿态评估系统"
    image = draw_chinese_text_enhanced(image, title_text, (x, current_y), 
                                     font_size=18, color=(0, 255, 255),
                                     background_color=(0, 0, 0), background_padding=3)
    current_y += line_height + 5
    
    # 绘制姿态信息
    if 'pose' in info_dict and info_dict['pose']:
        pose_info = info_dict['pose']
        pose_name = pose_info.get('pose', 'unknown')
        pose_conf = pose_info.get('confidence', 0.0)
        
        pose_chinese = get_pose_chinese_name(pose_name)
        pose_text = f"📊 姿态: {pose_chinese}"
        conf_text = f"   置信度: {pose_conf:.1%}"
        
        image = draw_chinese_text_enhanced(image, pose_text, (x, current_y), 
                                         font_size=16, color=(255, 255, 255))
        current_y += line_height
        
        image = draw_chinese_text_enhanced(image, conf_text, (x, current_y), 
                                         font_size=14, color=(200, 200, 200))
        current_y += line_height
    
    # 绘制动作信息
    if 'action' in info_dict and info_dict['action']:
        action_info = info_dict['action']
        action_name = action_info.get('action', 'unknown')
        action_conf = action_info.get('confidence', 0.0)
        
        action_chinese = get_action_chinese_name(action_name)
        action_text = f"🏃 动作: {action_chinese}"
        conf_text = f"   置信度: {action_conf:.1%}"
        
        image = draw_chinese_text_enhanced(image, action_text, (x, current_y), 
                                         font_size=16, color=(0, 255, 0))
        current_y += line_height
        
        image = draw_chinese_text_enhanced(image, conf_text, (x, current_y), 
                                         font_size=14, color=(200, 200, 200))
        current_y += line_height
    
    # 绘制行为信息
    if 'behavior' in info_dict and info_dict['behavior']:
        behavior_info = info_dict['behavior']
        behavior_name = behavior_info.get('chinese_name', '未知')
        behavior_conf = behavior_info.get('confidence', 0.0)
        
        behavior_text = f"🧠 行为: {behavior_name}"
        conf_text = f"   置信度: {behavior_conf:.1%}"
        
        image = draw_chinese_text_enhanced(image, behavior_text, (x, current_y), 
                                         font_size=16, color=(255, 0, 255))
        current_y += line_height
        
        image = draw_chinese_text_enhanced(image, conf_text, (x, current_y), 
                                         font_size=14, color=(200, 200, 200))
        current_y += line_height
    
    # 绘制操作提示
    current_y += 10
    tip_text = "💡 按 'q' 退出 | 按 's' 保存截图"
    image = draw_chinese_text_enhanced(image, tip_text, (x, current_y), 
                                     font_size=12, color=(255, 255, 0),
                                     background_color=(0, 0, 0), background_padding=2)
    
    return image

def get_pose_chinese_name(pose: str) -> str:
    """获取姿态的中文名称"""
    pose_names = {
        'standing': '站立',
        'sitting': '坐下',
        'lying_down': '躺下',
        'squatting': '蹲下',
        'walking': '步行',
        'unknown': '未识别'
    }
    return pose_names.get(pose, '未知')

def get_action_chinese_name(action: str) -> str:
    """获取动作的中文名称"""
    action_names = {
        'stationary': '静止',
        'moving': '移动',
        'walking': '步行',
        'waving': '挥手',
        'raising_hand': '举手',
        'unknown': '未知'
    }
    return action_names.get(action, '未知')

def test_chinese_display():
    """测试中文显示功能"""
    print("测试中文显示功能...")
    
    # 创建测试图像
    test_image = np.zeros((400, 600, 3), dtype=np.uint8)
    test_image.fill(50)  # 深灰色背景
    
    # 测试信息
    test_info = {
        'pose': {'pose': 'sitting', 'confidence': 0.85},
        'behavior': {'chinese_name': '工作', 'confidence': 0.75}
    }
    
    # 创建中文信息面板
    result_image = create_info_panel_chinese(test_image, test_info)
    
    # 显示结果
    cv2.imshow('中文显示测试', result_image)
    print("按任意键关闭测试窗口...")
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
    print("✅ 中文显示测试完成")

if __name__ == '__main__':
    test_chinese_display()
